package models

import (
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"short_domain/utils"
)

type Domain struct {
	Id    int64  `json:"id"`
	Url   string `json:"url"`
	Short string `json:"short"`
}

func CreateDomain(domain *Domain) (*Domain, error) {
	_, err := orm.NewOrm().Insert(domain)
	if err != nil {
		logs.Error("create domain failure ", err)
		return nil, err
	}

	return domain, nil
}

func GetDomainByUrl(query string) (*Domain, error) {
	p := &Domain{Url: query}
	if err := orm.NewOrm().QueryTable(new(Domain)).Filter("Url", query).RelatedSel().One(p); err == nil {
		return p, nil
	}

	p.Short = utils.MakeShort(query)
	_, err := orm.NewOrm().Insert(p)
	if err != nil {
		logs.Error("create Domain failure ", err)
		return nil, err
	}
	return p, nil
}

func GetDomainByShort(short string) (*Domain, error) {
	p := &Domain{Short: short}
	if err := orm.NewOrm().QueryTable(new(Domain)).Filter("Short", short).RelatedSel().One(p); err != nil {
		return nil, err
	}
	return p, nil
}
